package com.benmei.weike.web;

import com.benmei.weike.common.Constants;
import com.benmei.weike.common.Lang;
import com.benmei.weike.dto.PageResponse;
import com.benmei.weike.dto.mcCourse.*;
import com.benmei.weike.entity.Banner;
import com.benmei.weike.entity.McCourseCategory;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.exception.ServerException;
import com.benmei.weike.service.McCourseStudentService;
import com.benmei.weike.service.common.MemcachedService;
import com.benmei.weike.util.JsonUtil;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 学生端 系统课接口（V5.0 上课形式：1个老师多个学生）
 */
@RestController
@RequestMapping(value = "/mcCourse/v5.0/student")
public class McCourseStudentController {

    public static final Logger logger = LoggerFactory.getLogger(McCourseStudentController.class);

    @Autowired
    private MemcachedService memcachedService;
    @Autowired
    private McCourseStudentService mcCourseStudentService;

    // 1. 系统课 首页
    @RequestMapping(value = "/find/index", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo studentFindIndex(@RequestBody StudentFindIndexRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(req));

            // 如果有token，就读取membId,否则返回null
            Integer memb_id = memcachedService.tryGetMembId(token);

            Map<String, Object> obj = new HashedMap();
            // 1. 系统课banner
            List<Banner> bannerList = mcCourseStudentService.findBanner();
            obj.put("bannerList", bannerList);

            // 2. 系统课分类
            List<McCourseCategory> categoryList = mcCourseStudentService.findCategory();
            obj.put("categoryList", categoryList);

            // 3. 最近要上课的提醒信息（课程名称，上课时间：使用接口：/app/14/token/index/appointment/upcoming的数据，这里不再查询）

            // 4. 系统课列表
            PageResponse<McCourseDto> mcCoursePageData = mcCourseStudentService.findMcCourse(req, memb_id);
            obj.put("mcCoursePageData", mcCoursePageData);

            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(obj);
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 2 系统课 详情
    @RequestMapping(value = "/detail", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo mcCourseDetail(@RequestBody McCourseDetailRequest req, @RequestHeader(value = "token", required = false) String token) {
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(req));

            if (req.getMcCourseId() == null || req.getMcCourseId().intValue() == 0) {
                throw new ClientException("参数'mcCourseId'不能为空");
            }
            // 如果有token，就读取membId,否则返回null
            Integer memb_id = memcachedService.tryGetMembId(token);

            McCourseDetailResponse response = mcCourseStudentService.mcCourseDetail(req.getMcCourseId(), memb_id);
            RetInfo retInfo = RetInfo.getSuccessInfo();
            retInfo.setObj(response);
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }catch (ClientException e) {
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 3 预约系统课
    @RequestMapping(value = "/token/appointment", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo mcCourseAppointment(@RequestBody McCourseAppointmentRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            if (req.getMcCourseId() == null || req.getMcCourseId() == 0) {
                throw new ClientException("参数错误：无效的mcCourseId：" + req.getMcCourseId());
            }
            mcCourseStudentService.mcCourseAppointment(req.getMcCourseId(), tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo("预约成功");
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 4 查询团购结果
    @RequestMapping(value = "/token/find/group/result", method = {RequestMethod.POST})
    @ResponseBody
    public RetInfo findGroupResult(@RequestBody McCourseAppointmentRequest req, @RequestHeader(value = "token") String token) {
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(req));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            if (req.getMcCourseId() == null || req.getMcCourseId() == 0) {
                throw new ClientException("参数错误：无效的mcCourseId：" + req.getMcCourseId());
            }
            Map<String,String> result  = mcCourseStudentService.findGroupResultUrl(req.getMcCourseId(), tdNtMember.getMemb_id());

            RetInfo retInfo = RetInfo.getSuccessInfo("成功");
            retInfo.setObj(result);
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 5 进入教室
    @RequestMapping(value = "/token/intoMcCourseClassRoom", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo studentIntoClassRoom(@RequestBody McCourseIntoClassRoomRequest request,
                                        @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(request));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            if(request.getMc_course_schedule_id()==null){
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter 'mc_course_schedule_id' is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }

            McCourseIntoClassRoomResponse response = mcCourseStudentService.intoClassRoom(request.getMc_course_schedule_id(), tdNtMember.getMemb_id());
            RetInfo retInfo = RetInfo.getSuccessInfo(response);
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ServerException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // 6 离开教室
    @RequestMapping(value = "/token/leaveMcCourseClassRoom", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo studentLeaveClassRoom(@RequestBody McCourseIntoClassRoomRequest request,
                                         @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(request));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            mcCourseStudentService.leaveClassRoom(request.getMc_course_schedule_id(),tdNtMember.getMemb_id());
            RetInfo retInfo = RetInfo.getSuccessInfo();
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ServerException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
}
